﻿using APICommond;
using BusinessEntity.Warning;
using learun.util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Nacos.AspNetCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using BusinessEntity.U8;
using BusinessRule;
using BusinessEntity;

namespace Assets.API.Controllers
{
    public class ContractController : MvcControllerBase
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly INacosServerManager _serverManager;
        public ContractController(INacosServerManager serverManager, IHttpClientFactory httpClientFactory) : base(serverManager)
        {
            _serverManager = serverManager;
            _httpClientFactory = httpClientFactory;
        }

        #region "合同"
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> SaveMoney([FromBody] ContractMoneyInfo info)
        {
            try
            {
                await BusinessRule.Warning.Waring.SaveMoney(info);
                return Success("成功！");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> SaveContractPlan([FromBody] ContractPlan plan)
        {
            try
            {
                await BusinessRule.Warning.Waring.SaveContractPlan( plan.projcode, plan.bz, Convert.ToDateTime(plan.skrq), Convert.ToDecimal(plan.je), plan.sqbl, plan.nd, "", "");
                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> SaveContractPlans(dynamic plans)
        {
            try
            {
                string projcode = plans["projcode"].ToString();
                JArray pls = (JArray)plans["plans"];
                await BusinessRule.Warning.Waring.DeleteContractPlanByProjcode(projcode);
                foreach (JObject plan in pls)
                {
                    int id = 0;
                    
                        if (plan.Property("ID") != null)
                        {
                            int.TryParse(plan["id"].ToString(), out id);
                        }
                        
                    
                    string bz = "";
                    if (plan.Property("bz") != null)
                    {
                        bz = plan["bz"].ToString();
                    }
                    DateTime skrq = DateTime.Today;
                    if (plan.Property("skrq") != null)
                    {
                        skrq = Convert.ToDateTime(plan["skrq"]);
                    }
                    decimal je = 0;
                    if (plan.Property("je") != null)
                    {
                        je = Convert.ToDecimal(plan["je"]);
                    }
                    string sqbl = "";
                    if (plan.Property("sqbl") != null)
                    {
                        sqbl = Convert.ToString(plan["sqbl"]);
                    }
                    string nd = "";
                    if (plan.Property("nd") != null)
                    {
                        nd = Convert.ToString(plan["nd"]);
                    }
                    await BusinessRule.Warning.Waring.SaveContractPlan( projcode, bz, skrq, je, sqbl, nd, "", "");
                }
                    return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DeleteContractPlan(int id)
        {
            try
            {
                await BusinessRule.Warning.Waring.DeleteContractPlan(id);
                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<BackEntity> ReceiveData([FromBody] object str)
        {

            BackEntity backEntity = new BackEntity();
            string s = str.ToString();
            try
            {
                //s = s.ToLower();
                JObject jobject = JObject.Parse(s);
                string type = "";
                if (jobject.Property("type") != null)
                {
                    type = jobject["type"].ToString();
                }
                string area = "";
                if (jobject.Property("area") != null)
                {
                    area = jobject["area"].ToString();
                }
                string timeStamp = "";
                if (jobject.Property("timeStamp") != null)
                {
                    timeStamp = jobject["timeStamp"].ToString();
                }
                string accessToken = "";
                if (jobject.Property("accessToken") != null)
                {
                    accessToken = jobject["accessToken"].ToString();
                }

                string transId = "";
                if (jobject.Property("transId") != null)
                {
                    transId = jobject["transId"].ToString();
                }

                string md5 = APICommond.DataToEntity.GetMD5(area + type + transId + timeStamp);
                if (md5.ToLower() != accessToken.ToLower())
                {
                    backEntity.code = "202";
                    backEntity.message = "MD5验证失败";
                    backEntity.transId = transId;
                    return backEntity;
                }

                //System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
                //DateTime dt = startTime.AddSeconds(Convert.ToInt64(timeStamp));
                ////dtStart = dtStart.Add(toNow);
                //if (dt.AddMinutes(1).Minute > dt.Minute)
                //{
                //    backEntity.Code = "203";
                //    backEntity.Message = "timeStamp与当前时间相差1分钟以上";
                //    backEntity.transId = transId;
                //    return backEntity;
                //}
                JObject ja = null;
                if (jobject.Property("data") != null)
                {
                    ja = JObject.Parse(jobject["data"].ToString());
                }
                string ver = "";
                if (ja != null && ja.Count > 0)
                {
                    ver = await BusinessRule.Warning.Waring.InsertContract(ja);
                }
                if (ver == "")
                {
                    backEntity.code = "200";
                    backEntity.message = "成功";
                    backEntity.transId = transId;
                }
                else
                {
                    backEntity.code = "204";
                    backEntity.message = "数据处理失败" + ver;
                }
            }
            catch (Exception ex)
            {
                backEntity.code = "999";
                backEntity.message = "其他错误" + ex.Message;
                //backEntity.transId = transId;
            }
            string err = await BusinessRule.Warning.Waring.InsertMessage(s, JsonConvert.SerializeObject(backEntity));
            return backEntity;
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetProjects(string crf = "", string xmbh = "", string xmmc = "", string jylx = "", string cjzt = "", int current = 1, int size = 20)
        {
            _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);


            (DataTable, int) SelectTable = await BusinessRule.Warning.Waring.GetProject(crf, xmbh, xmmc, jylx, cjzt, size, current);
            DataTable table = SelectTable.Item1;
            //table = DateString.Dateformat(table);
            Page pa = new Page();
            pa.records = table;
            pa.total = SelectTable.Item2;

            _logger.Log(LogLevel.Info, Success(pa).ToJson());
            return Success(pa, true);
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetProjectInfo(string projcode)
        {
            _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);


            DataTable pr = await BusinessRule.Warning.Waring.Getpro(projcode);
            DataTable assp = await BusinessRule.Warning.Waring.GetAssetP(projcode);
            ProjectInfo info = new ProjectInfo();
            info.project = DataToEntity.DataTableToEntity<Project>(pr);
            List<AssetP> list = new List<AssetP>();
            list = DataToEntity.DataTableToEntityList<AssetP>(assp) as List<AssetP>;
            info.asset = list;

            return Success(info, true);
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetSend(string org = "", string crf = "", string zcbm = "", string zcmc = "", string start = "", string end = "", string zt = "", int current = 1, int size = 20)
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                string orgs = await Getorg();
                if (!org.Contains(orgs))
                {
                    org = orgs;
                }


                (IEnumerable<dynamic>, int) SelectTable = await BusinessRule.Warning.Waring.GetSend(org, crf, zcbm, zcmc, start, end, zt, current, size);
                //DataTable table = SelectTable.Item1;
                //table = DateString.Dateformat(table);
                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;

                _logger.Log(LogLevel.Info, Success(pa).ToJson());
                return Success(pa, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }


        #endregion

        #region "产权交易中心"
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> SaveProject(string projcode)
        {
            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string guiid = Guid.NewGuid().ToString();
            var client = _httpClientFactory.CreateClient();
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            string body = "{\"appkey\":\"" + ConfigHelper.GetConfig().key + "\",\"projcode\":\"" + projcode + "\"}";
            //string body = "{\"projcode\":\"" + procode + "\"}";
            JObject j = JObject.Parse(body);
            //转为链接需要的格式
            HttpContent httpContent = new JsonContent(j);
            //client.BaseAddress = new Uri(ConfigHelper.GetConfig().asset);
            client.DefaultRequestHeaders.Add("appkey", ConfigHelper.GetConfig().key);
            client.DefaultRequestHeaders.Add("time", time);
            client.DefaultRequestHeaders.Add("guid", guiid);
            client.DefaultRequestHeaders.Add("sign", APICommond.CreateHeader.ToMD5String(ConfigHelper.GetConfig().key + time + guiid + JsonConvert.SerializeObject(j) + ConfigHelper.GetConfig().secret));
            string result = "";
            HttpResponseMessage response = client.PostAsync(ConfigHelper.GetConfig().asset + "projectpublish", httpContent).Result;
            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                if (t != null)
                {
                    result = t.Result;
                    JObject j1 = JObject.Parse(t.Result);
                    if (j1["status"].ToString() == "True")
                    {
                        JObject jb = JObject.Parse(j1["data"].ToString());
                        await BusinessRule.Warning.Waring.SaveProject(jb);
                        return Success(jb);
                    }

                }
            }

            return Fail(result);


        }


        //[HttpPost]
        //[AllowAnonymous]
        //public async Task<IActionResult> Intendedtransferee(string projcode)
        //{
        //    string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        //    string guiid = Guid.NewGuid().ToString();
        //    var client = _httpClientFactory.CreateClient();
        //    client.DefaultRequestHeaders.Accept.Clear();
        //    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        //    string body = "{\"appkey\":\"" + ConfigHelper.GetConfig().key + "\",\"projcode\":\"" + projcode + "\"}";
        //    //string body = "{\"projcode\":\"" + procode + "\"}";
        //    JObject j = JObject.Parse(body);
        //    //转为链接需要的格式
        //    HttpContent httpContent = new JsonContent(j);
        //    //client.BaseAddress = new Uri(ConfigHelper.GetConfig().asset);
        //    client.DefaultRequestHeaders.Add("appkey", ConfigHelper.GetConfig().key);
        //    client.DefaultRequestHeaders.Add("time", time);
        //    client.DefaultRequestHeaders.Add("guid", guiid);
        //    client.DefaultRequestHeaders.Add("sign", APICommond.CreateHeader.ToMD5String(ConfigHelper.GetConfig().key + time + guiid + JsonConvert.SerializeObject(j) + ConfigHelper.GetConfig().secret));
        //    string result = "";
        //    HttpResponseMessage response = client.PostAsync(ConfigHelper.GetConfig().asset + "intendedtransferee", httpContent).Result;
        //    if (response.IsSuccessStatusCode)
        //    {
        //        Task<string> t = response.Content.ReadAsStringAsync();
        //        if (t != null)
        //        {
        //            result = t.Result;
        //            JObject j1 = JObject.Parse(t.Result);
        //            if (j1["status"].ToString() == "True")
        //            {
        //                JObject jb = JObject.Parse(j1["data"].ToString());
        //                await BusinessRule.Warning.Waring.SaveIntendedtransferee(jb);
        //                return Success("成功");
        //            }

        //        }
        //    }

        //    return Fail(result);


        //}

        //[HttpPost]
        //[AllowAnonymous]
        //public async Task<IActionResult> Projectendresult(string projcode)
        //{
        //    string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        //    string guiid = Guid.NewGuid().ToString();
        //    var client = _httpClientFactory.CreateClient();
        //    client.DefaultRequestHeaders.Accept.Clear();
        //    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        //    string body = "{\"appkey\":\"" + ConfigHelper.GetConfig().key + "\",\"projcode\":\"" + projcode + "\"}";
        //    //string body = "{\"projcode\":\"" + procode + "\"}";
        //    JObject j = JObject.Parse(body);
        //    //转为链接需要的格式
        //    HttpContent httpContent = new JsonContent(j);
        //    //client.BaseAddress = new Uri(ConfigHelper.GetConfig().asset);
        //    client.DefaultRequestHeaders.Add("appkey", ConfigHelper.GetConfig().key);
        //    client.DefaultRequestHeaders.Add("time", time);
        //    client.DefaultRequestHeaders.Add("guid", guiid);
        //    client.DefaultRequestHeaders.Add("sign", APICommond.CreateHeader.ToMD5String(ConfigHelper.GetConfig().key + time + guiid + JsonConvert.SerializeObject(j) + ConfigHelper.GetConfig().secret));
        //    string result = "";
        //    HttpResponseMessage response = client.PostAsync(ConfigHelper.GetConfig().asset + "projectendresult", httpContent).Result;
        //    if (response.IsSuccessStatusCode)
        //    {
        //        Task<string> t = response.Content.ReadAsStringAsync();
        //        if (t != null)
        //        {
        //            result = t.Result;
        //            JObject j1 = JObject.Parse(t.Result);
        //            if (j1["status"].ToString() == "True")
        //            {
        //                JObject jb = JObject.Parse(j1["data"].ToString());
        //                await BusinessRule.Warning.Waring.SaveProjectendresult(jb);
        //                return Success("成功");
        //            }

        //        }
        //    }

        //    return Fail(result);


        //}

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> SaveContract(string projcode)
        {
            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string guiid = Guid.NewGuid().ToString();
            var client = _httpClientFactory.CreateClient();
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            string body = "{\"appkey\":\"" + ConfigHelper.GetConfig().key + "\",\"projcode\":\"" + projcode + "\"}";
            //string body = "{\"projcode\":\"" + procode + "\"}";
            JObject j = JObject.Parse(body);
            //转为链接需要的格式
            HttpContent httpContent = new JsonContent(j);
            //client.BaseAddress = new Uri(ConfigHelper.GetConfig().asset);
            client.DefaultRequestHeaders.Add("appkey", ConfigHelper.GetConfig().key);
            client.DefaultRequestHeaders.Add("time", time);
            client.DefaultRequestHeaders.Add("guid", guiid);
            client.DefaultRequestHeaders.Add("sign", APICommond.CreateHeader.ToMD5String(ConfigHelper.GetConfig().key + time + guiid + JsonConvert.SerializeObject(j) + ConfigHelper.GetConfig().secret));
            string result = "";
            HttpResponseMessage response = client.PostAsync(ConfigHelper.GetConfig().asset + "contractinformation", httpContent).Result;
            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                if (t != null)
                {
                    result = t.Result;
                    JObject j1 = JObject.Parse(t.Result);
                    if (j1["status"].ToString() == "True")
                    {
                        JObject jb = JObject.Parse(j1["data"].ToString());
                        await BusinessRule.Warning.Waring.InsertContract(jb);
                        return Success(jb);
                    }

                }
            }

            return Fail(result);


        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetKey()
        {
            try
            {
                // _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                string zcdm = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                _logger.Log(LogLevel.Info, Success(zcdm).ToJson());
                return Success(zcdm);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> SendAssets([FromBody] JObject str)
        {
            #region "处理接收到的参数"
            //保存传入的参数
            FileUploadent filecodes = new FileUploadent();
            if (null != str["fileUpload"])
            {
                filecodes = str["fileUpload"].ToObject<FileUploadent>();
            }
            string id = "";
            string sope = "add";
            if (str.Property("sope") != null)
            {
                sope = str["sope"].ToString();
            }

            if (sope == "add")
            {
                id = str["id"].ToString();
                if (id != "")
                {
                    await BusinessRule.Warning.Waring.UpdateSend(str, "0");
                }
                else
                {
                    id = await BusinessRule.Warning.Waring.SaveSend(str);
                }
                //filecodes.version = id;
                JArray ja = JArray.Parse(str["assets"].ToString());
                foreach (JObject jb in ja)
                {
                    DataTable dt = await BusinessRule.Warning.Waring.GetSendAssets(id);
                    string zcid = "";
                    if (dt.Rows.Count > 0)
                    {
                        if (Convert.ToString(dt.Rows[0]["zcbm"]) == jb["assetcode"].ToString())
                        {
                            zcid = Convert.ToString(dt.Rows[0]["Assetid"]);
                        }
                    }
                    await JavaApi.UploadFileJavaAPI(zcid, filecodes, await GetICApiInfo());
                }
            }
            else if (sope == "edit")
            {
                id = str["id"].ToString();
                if (id == "")
                {
                    id = await BusinessRule.Warning.Waring.SaveSend(str);
                }
                else
                {
                    await BusinessRule.Warning.Waring.UpdateSend(str, "0");
                }

                //filecodes.version = id;
                JArray ja = JArray.Parse(str["assets"].ToString());
                foreach (JObject jb in ja)
                {
                    DataTable dt = await BusinessRule.Warning.Waring.GetSendAssets(id);
                    string zcid = "";
                    if (dt.Rows.Count > 0)
                    {
                        if (Convert.ToString(dt.Rows[0]["zcbm"]) == jb["assetcode"].ToString())
                        {
                            zcid = Convert.ToString(dt.Rows[0]["Assetid"]);
                        }
                    }
                    await JavaApi.UploadFileJavaAPI(zcid, filecodes, await GetICApiInfo());
                }
            }
            else if (sope == "submit")
            {
                id = str["id"].ToString();
                if (id == "")
                {
                    id = await BusinessRule.Warning.Waring.SaveSend(str);
                    //filecodes.version = id;
                    if (str.Property("id") != null)
                    {
                        str.Remove("id");
                    }
                    str.Add("id", id);
                    //str["id"] = id;
                    JArray ja = JArray.Parse(str["assets"].ToString());
                    foreach (JObject jb in ja)
                    {
                        DataTable dt = await BusinessRule.Warning.Waring.GetSendAssets(id);
                        string zcid = "";
                        if (dt.Rows.Count > 0)
                        {
                            if (Convert.ToString(dt.Rows[0]["zcbm"]) == jb["assetcode"].ToString())
                            {
                                zcid = Convert.ToString(dt.Rows[0]["Assetid"]);
                            }
                        }
                        await JavaApi.UploadFileJavaAPI(zcid, filecodes, await GetICApiInfo());
                    }
                }

                //bsp = false;

                //var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.合同修改记录.ToString(), ht.id);

                JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = id, amount = "", content = "发布资产" + id, deptName = GetUserDeptName() };
                JavaApi.SPLEnt spl = new JavaApi.SPLEnt();
                spl.businessName = "发布资产";
                spl.businessId = id;
                // spl.publicParamKey = "FEE_PROCESS";
                spl.formCode = filecodes.formCode;
                spl.description = _description.ToJson();
                JObject s = JObject.Parse(str.ToString());
                s.Remove("assets");
                spl.additionInfoJson = Newtonsoft.Json.JsonConvert.SerializeObject(s);
                spl.callbackUrl = "http://ic-xmzc/netapi/Contract/UpdateStatus";
                spl.callbackInterface = "/contract-rule/assets-form/${taskId}/" + id + "/audit";
                spl.callbackView = "/contract-rule/assets-form/" + id + "/view";
                //JavaApi.SPLEnt spl = new JavaApi.SPLEnt("资产发布",id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(str), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                bool bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                //if (!bsp)
                string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                //ht.spl = strInstanceId;
                if (strInstanceId.StartsWith("err"))
                {
                    return Fail("提交失败，启动工作流异常");
                }
                else
                {
                    if (str["id"].ToString() != "")
                    {
                        await BusinessRule.Warning.Waring.UpdateSend(str, "0");
                    }
                    JArray ja = JArray.Parse(str["assets"].ToString());
                    foreach (JObject jb in ja)
                    {
                        DataTable dt = await BusinessRule.Warning.Waring.GetSendAssets(id);
                        string zcid = "";
                        if (dt.Rows.Count > 0)
                        {
                            if (Convert.ToString(dt.Rows[0]["zcbm"]) == jb["assetcode"].ToString())
                            {
                                zcid = Convert.ToString(dt.Rows[0]["Assetid"]);
                            }
                        }
                        await JavaApi.UploadFileJavaAPI(zcid, filecodes, await GetICApiInfo());
                    }
                }
            }
            else
            {
                id = str["id"].ToString();
                if (id == "")
                {
                    id = await BusinessRule.Warning.Waring.SaveSend(str);
                    //filecodes.version = id;
                    if (str.Property("id") != null)
                    {
                        str.Remove("id");
                    }
                    str.Add("id", id);
                    //str["id"] = id;
                    JArray ja = JArray.Parse(str["assets"].ToString());
                    foreach (JObject jb in ja)
                    {
                        DataTable dt = await BusinessRule.Warning.Waring.GetSendAssets(id);
                        string zcid = "";
                        if (dt.Rows.Count > 0)
                        {
                            if (Convert.ToString(dt.Rows[0]["zcbm"]) == jb["assetcode"].ToString())
                            {
                                zcid = Convert.ToString(dt.Rows[0]["Assetid"]);
                            }
                        }
                        await JavaApi.UploadFileJavaAPI(zcid, filecodes, await GetICApiInfo());
                    }
                }
                else
                {
                    await BusinessRule.Warning.Waring.UpdateSend(str, "1");
                    JArray ja = JArray.Parse(str["assets"].ToString());
                    foreach (JObject jb in ja)
                    {
                        DataTable dt = await BusinessRule.Warning.Waring.GetSendAssets(id);
                        string zcid = "";
                        if (dt.Rows.Count > 0)
                        {
                            if (Convert.ToString(dt.Rows[0]["zcbm"]) == jb["assetcode"].ToString())
                            {
                                zcid = Convert.ToString(dt.Rows[0]["Assetid"]);
                            }
                        }
                        await JavaApi.UploadFileJavaAPI(zcid, filecodes, await GetICApiInfo());
                    }
                }
                DataTable data = await BusinessRule.Warning.Waring.GetSendAssets(id);
                DataTable send = await BusinessRule.Warning.Waring.GetSend(id);
                DataRow row = send.Rows[0];
                SendAsset asset = new SendAsset();
                asset.appkey = ConfigHelper.GetConfig().key;
                asset.acctnumb = row["areacode"].ToString();
                asset.acctname = row["areaname"].ToString();
                asset.bankname = row["bankname"].ToString();
                asset.bankno = row["bankno"].ToString();
                asset.contractperson = row["contractperson"].ToString();
                asset.dutyperson = row["dutyperson"].ToString();
                asset.mobilephone = row["mobilephone"].ToString();
                asset.transferorname = row["orgname"].ToString();
                //JArray jax = JArray.Parse(str["assets"].ToString());
                List<Assetd> listd = new List<Assetd>();
                foreach (DataRow sr in data.Rows)
                {
                    string zcbm = sr["zcbm"].ToString();
                    DataTable dataTable = await BusinessRule.Warning.U8Data.GetZCKP(zcbm);
                    Assetd assetd = new Assetd();
                    if (dataTable.Rows.Count > 0)
                    {
                        DataRow dr = dataTable.Rows[0];
                        assetd.assetcode = Convert.ToString(dr["assetcode"]);
                        assetd.assetname = Convert.ToString(dr["assetname"]);
                        assetd.assetclass = Convert.ToString(dr["assetclass"]);
                        assetd.assettype = Convert.ToString(dr["assettype"]);
                        assetd.assetsite = Convert.ToString(dr["assetsite"]);
                        assetd.resourcetype = Convert.ToString(dr["resourcetype"]);
                        assetd.tradeunit = Convert.ToString(dr["tradeunit"]);
                        assetd.orgid = Convert.ToString(dr["orgid"]);

                        assetd.assetid = ConfigHelper.GetConfig().areacode + sr["Assetid"].ToString();
                        assetd.tradearea = sr["mj"].ToString();

                        DataTable dt = await BusinessRule.Warning.Waring.GetAssetFile(id, zcbm);
                        List<BusinessEntity.Warning.Files> listf = new List<BusinessEntity.Warning.Files>();
                        foreach (DataRow r in dt.Rows)
                        {
                            BusinessEntity.Warning.Files f = new BusinessEntity.Warning.Files();
                            f.filename = Convert.ToString(r["filename"]);
                            f.fileurl = Convert.ToString(r["fileurl"]);
                            listf.Add(f);
                        }
                        assetd.attachments = listf;
                        listd.Add(assetd);
                    }
                    else
                    {
                        return Fail("传入的资产在资产卡片中不存在！");
                        // return Json(new ResParameter { code = ResponseCode.fail, message = "传入的资产在资产卡片中不存在" });
                    }
                }
                asset.assets = listd;



                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string guiid = Guid.NewGuid().ToString();
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


                //string body = "{\"projcode\":\"" + procode + "\"}";
                //JObject j = JObject.Parse(body);
                //转为链接需要的格式
                HttpContent httpContent = new JsonContent(asset);
                //client.BaseAddress = new Uri(ConfigHelper.GetConfig().asset);
                client.DefaultRequestHeaders.Add("appkey", ConfigHelper.GetConfig().key);
                client.DefaultRequestHeaders.Add("time", time);
                client.DefaultRequestHeaders.Add("guid", guiid);
                client.DefaultRequestHeaders.Add("sign", APICommond.CreateHeader.ToMD5String(ConfigHelper.GetConfig().key + time + guiid + JsonConvert.SerializeObject(asset) + ConfigHelper.GetConfig().secret));
                string result = "";
                HttpResponseMessage response = client.PostAsync(ConfigHelper.GetConfig().asset + "entryassetinformation", httpContent).Result;
                if (response.IsSuccessStatusCode)
                {
                    Task<string> t = response.Content.ReadAsStringAsync();
                    if (t != null)
                    {
                        result = t.Result;
                        JObject j1 = JObject.Parse(t.Result);
                        if (j1["status"].ToString() == "True")
                        {
                            JObject jb = JObject.Parse(j1["data"].ToString());
                            await BusinessRule.Warning.Waring.InsertContract(jb);
                            string err = await BusinessRule.Warning.Waring.InsertMessage(JsonConvert.SerializeObject(asset), JsonConvert.SerializeObject(t.Result));
                            //return Success("成功");
                        }
                        else
                        {
                            string err = await BusinessRule.Warning.Waring.InsertMessage(JsonConvert.SerializeObject(asset), JsonConvert.SerializeObject(t.Result));
                            return Fail("产交系统返回错误信息");
                            // return Json(new ResParameter { code = ResponseCode.fail, message = "产交系统返回错误信息" });
                        }

                    }
                }
            }

            #endregion
            return Success("成功");
        }
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> Project([FromBody] JObject str)
        {
            try
            {
                _logger.Debug(JsonConvert.SerializeObject(str));

                await BusinessRule.Warning.Waring.SaveProject1(str);
                //return SuccessCenter("成功", "true");
                string projcode = Convert.ToString(str["projcode"]);
                string functioncode = Convert.ToString(str["functioncode"]);
                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string guiid = Guid.NewGuid().ToString();
                var handler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true,
                    ClientCertificateOptions = ClientCertificateOption.Manual,
                };
                using (var client = new HttpClient(handler))
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    string body = "{\"appkey\":\"" + ConfigHelper.GetConfig().key + "\",\"projcode\":\"" + projcode + "\"}";
                    //string body = "{\"projcode\":\"" + procode + "\"}";
                    JObject j = JObject.Parse(body);
                    //转为链接需要的格式
                    HttpContent httpContent = new JsonContent(j);
                    //client.BaseAddress = new Uri(ConfigHelper.GetConfig().asset);
                    client.DefaultRequestHeaders.Add("appkey", ConfigHelper.GetConfig().key);
                    client.DefaultRequestHeaders.Add("time", time);
                    client.DefaultRequestHeaders.Add("guid", guiid);
                    client.DefaultRequestHeaders.Add("sign", APICommond.CreateHeader.ToMD5String(ConfigHelper.GetConfig().key + time + guiid + JsonConvert.SerializeObject(j) + ConfigHelper.GetConfig().secret));
                    string result = "";
                    switch (functioncode)
                    {
                        case "8"://项目立项
                            HttpResponseMessage response = client.PostAsync(ConfigHelper.GetConfig().asset + "projectpublish", httpContent).Result;
                            _logger.Debug("收到的报文：" + response.Content);
                            if (response.IsSuccessStatusCode)
                            {
                                Task<string> t = response.Content.ReadAsStringAsync();
                                if (t != null)
                                {
                                    result = t.Result;
                                    _logger.Debug("收到的报文：" + result);
                                    JObject j1 = JObject.Parse(t.Result);
                                    if (j1["status"].ToString() == "True")
                                    {
                                        string data = j1["data"].ToString();
                                        try
                                        {
                                            data = DES.DecryptDES(data, ConfigHelper.GetConfig().desKey);
                                            _logger.Debug("解密后的报文：" + data);
                                            JObject jb = JObject.Parse(data);
                                            await BusinessRule.Warning.Waring.SaveProject(jb);
                                            string err = await BusinessRule.Warning.Waring.InsertMessage(JsonConvert.SerializeObject(j), JsonConvert.SerializeObject(t.Result)+data);
                                        }
                                        catch (Exception e)
                                        {
                                            _logger.Debug("回调接口contractinformation解密失败" + e.Message);
                                        }

                                        //return SuccessCenter("成功", "true");
                                    }
                                    else
                                    {
                                        _logger.Debug("回调接口contractinformation解密失败");
                                    }
                                }
                            }
                            else
                            {
                                _logger.Debug("回调接口失败");
                            }
                            break;
                        case "6"://合同录入
                            HttpResponseMessage response1 = client.PostAsync(ConfigHelper.GetConfig().asset + "contractinformation", httpContent).Result;
                            if (response1.IsSuccessStatusCode)
                            {
                                Task<string> t = response1.Content.ReadAsStringAsync();
                                if (t != null)
                                {
                                    result = t.Result;
                                    _logger.Debug("收到的报文：" + result);
                                    JObject j1 = JObject.Parse(t.Result);
                                    if (j1["status"].ToString() == "True")
                                    {
                                        string data = j1["data"].ToString();
                                        try
                                        {
                                            data = DES.DecryptDES(data, ConfigHelper.GetConfig().desKey);
                                            _logger.Debug("解密后：" + data);
                                            JObject jb = JObject.Parse(data);
                                            jb["projresult"] = 12;
                                            await BusinessRule.Warning.Waring.SaveProjectendresult(jb);
                                            
                                           string ver=  await BusinessRule.Warning.Waring.InsertContract(jb);
                                            if (ver == "")
                                            {
                                                _logger.Debug("合同数据保存成功");
                                            }
                                            else
                                            { _logger.Debug("合同数据保存失败：" + ver); }
                                            
                                            string err = await BusinessRule.Warning.Waring.InsertMessage(JsonConvert.SerializeObject(j), JsonConvert.SerializeObject(t.Result)+data);
                                            //return SuccessCenter("成功", "true");
                                        }
                                        catch (Exception e)
                                        {
                                            _logger.Debug("回调接口contractinformation解密失败" + e.Message);
                                        }

                                    }
                                    else
                                    {
                                        _logger.Debug("回调接口contractinformation失败");
                                    }
                                }
                            }
                            break;
                        case "9"://项目状态
                            HttpResponseMessage response2 = client.PostAsync(ConfigHelper.GetConfig().asset + "projectendresult", httpContent).Result;
                            if (response2.IsSuccessStatusCode)
                            {
                                Task<string> t = response2.Content.ReadAsStringAsync();
                                if (t != null)
                                {
                                    result = t.Result;
                                    _logger.Debug("收到的报文：" + result);
                                    JObject j1 = JObject.Parse(t.Result);
                                    if (j1["status"].ToString() == "True")
                                    {
                                        string data = j1["data"].ToString();
                                        try
                                        {
                                            data = DES.DecryptDES(data, ConfigHelper.GetConfig().desKey);
                                            _logger.Debug("解密后：" + data);
                                            JObject jb = JObject.Parse(data);
                                            await BusinessRule.Warning.Waring.SaveProjectendresult(jb);
                                            await BusinessRule.Warning.Waring.InsertContract(jb);
                                            string err = await BusinessRule.Warning.Waring.InsertMessage(JsonConvert.SerializeObject(j), JsonConvert.SerializeObject(t.Result)+data);
                                            // return SuccessCenter("成功", "true");
                                        }
                                        catch (Exception e)
                                        {
                                            _logger.Debug("回调接口contractinformation解密失败" + e.Message);
                                        }

                                    }
                                    else
                                    {
                                        _logger.Debug("回调接口contractinformation失败");
                                    }
                                }
                            }
                            break;
                        case "10"://项目状态
                            HttpResponseMessage response21 = client.PostAsync(ConfigHelper.GetConfig().asset + "intendedtransferee", httpContent).Result;
                            if (response21.IsSuccessStatusCode)
                            {
                                Task<string> t = response21.Content.ReadAsStringAsync();
                                if (t != null)
                                {
                                    result = t.Result;
                                    _logger.Debug("收到的报文：" + result);
                                    JObject j1 = JObject.Parse(t.Result);
                                    if (j1["status"].ToString() == "True")
                                    {
                                        string data = j1["data"].ToString();
                                        try
                                        {
                                            data = DES.DecryptDES(data, ConfigHelper.GetConfig().desKey);
                                            JObject jb = JObject.Parse(data);
                                            await BusinessRule.Warning.Waring.SaveIntendedtransferee(jb);
                                            string err = await BusinessRule.Warning.Waring.InsertMessage(JsonConvert.SerializeObject(j), JsonConvert.SerializeObject(t.Result)+data);
                                            //return SuccessCenter("成功", "true");
                                        }
                                        catch (Exception e)
                                        {
                                            _logger.Debug("回调接口intendedtransferee解密失败" + e.Message);
                                        }

                                    }
                                    else
                                    {
                                        _logger.Debug("回调接口intendedtransferee失败");
                                    }
                                }
                            }
                            break;
                    }
                    //return SuccessCenter("失败", "false");
                }
                if (ConfigHelper.GetConfig().areacode == "096")
                {
                    JArray ja1 = JArray.Parse(str["assetids"].ToString());
                    if (ja1 != null)
                    {
                        _logger.Debug(ja1[0].ToString());
                        DataTable ta = await BusinessRule.Warning.Waring.GetAssets(ja1[0].ToString(), projcode);
                        if (ta.Rows.Count > 0)
                        {
                            _logger.Debug("开始调用资产公司接口");
                            using (var client = new HttpClient())
                            {
                                client.DefaultRequestHeaders.Accept.Clear();
                                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                                JArray ja = JArray.Parse(str["assetids"].ToString());
                                List<string> ss = new List<string>();
                                foreach (string jb in ja)
                                {
                                    ss.Add("100" + jb.ToString().Substring(3));
                                }
                                str.Remove("assetids");

                                str.Add("assetids", JArray.Parse(JsonConvert.SerializeObject(ss)));
                                HttpContent httpContent = new JsonContent(str);
                                _logger.Debug("调用参数：" + str.ToString());
                                HttpResponseMessage response1 = client.PostAsync(ConfigHelper.GetConfig().asseturl, httpContent).Result;
                                if (response1.IsSuccessStatusCode)
                                {
                                    Task<string> t = response1.Content.ReadAsStringAsync();
                                    if (t != null)
                                    {
                                        string result = t.Result;
                                        _logger.Debug("收到的报文：" + result);
                                        // JObject j1 = JObject.Parse(result);
                                        if (result.Contains("true"))
                                        {
                                            _logger.Debug("调用资产公司接口成功");
                                        }
                                        else
                                        {
                                            _logger.Debug("调用资产公司接口失败" + response1.RequestMessage);
                                        }
                                    }
                                    else
                                    {
                                        _logger.Debug("调用资产公司接口失败x" + response1.RequestMessage);
                                    }
                                }

                            }
                        }
                        else
                        {
                            _logger.Debug("不是娄葑的数据");
                        }
                    }
                }
                return SuccessCenter("成功", "true");
            }
            catch (Exception ex)
            {
                return SuccessCenter("失败" + ex.Message, "false");
            }
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> projectpublish(JObject proj)
        {
            try
            {
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                string projcode = proj["projcode"].ToString();
                DataTable pr = await BusinessRule.Warning.Waring.projectpublish(projcode);
                DataTable assp = await BusinessRule.Warning.Waring.projectpublishAssets(projcode);
                ProjectPublish info = new ProjectPublish();
                info = DataToEntity.DataTableToEntity<ProjectPublish>(pr);
                if (assp.Rows.Count > 0)
                {
                    List<passets> list = new List<passets>();
                    list = DataToEntity.DataTableToEntityList<passets>(assp) as List<passets>;
                    info.assets = list;
                }
                return SuccessCenter(info, "true");
            }
            catch (Exception ex)
            {
                return SuccessCenter("失败", "false");
            }
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> intendedtransferee(JObject proj)
        {
            try
            {
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                string projcode = proj["projcode"].ToString();
                DataTable pr = await BusinessRule.Warning.Waring.projectpublish(projcode);
                Intendedtransferee info = new Intendedtransferee();
                info = DataToEntity.DataTableToEntity<Intendedtransferee>(pr);
                return SuccessCenter(info, "true");
            }
            catch (Exception ex)
            {
                return SuccessCenter("失败", "false");
            }
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> projectendresult(JObject proj)
        {
            try
            {
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                string projcode = proj["projcode"].ToString();
                DataTable pr = await BusinessRule.Warning.Waring.projectpublish(projcode);
                Projectendresult info = new Projectendresult();
                info = DataToEntity.DataTableToEntity<Projectendresult>(pr);
                return SuccessCenter(info, "true");
            }
            catch (Exception ex)
            {
                return SuccessCenter("失败", "false");
            }
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> contractinformation(JObject proj)
        {
            try
            {
                string projcode = proj["projcode"].ToString();
                DataTable dataTable = await BusinessRule.Warning.Waring.GetContractInfo(projcode);

                ContractInfo1 info = new ContractInfo1();

                info = DataToEntity.DataTableToEntity<BusinessEntity.Warning.ContractInfo1>(dataTable);
                List<BusinessEntity.Warning.Assets> lista = new List<BusinessEntity.Warning.Assets>();
                DataTable zc = await BusinessRule.Warning.Waring.GetContractAssetsInfo1(projcode);

                lista = DataToEntity.DataTableToEntityList<BusinessEntity.Warning.Assets>(zc) as List<BusinessEntity.Warning.Assets>;
                if (lista != null)
                {
                    info.assets = lista;
                }
                List<ContractFile> files = new List<ContractFile>();
                DataTable f = await BusinessRule.Warning.Waring.GetContractFileInfo(projcode);
                files = DataToEntity.DataTableToEntityList<ContractFile>(f) as List<ContractFile>;
                if (files != null)
                {
                    info.contractfile = files;
                }
                List<ContractPlan> listp = new List<ContractPlan>();
                DataTable p = await BusinessRule.Warning.Waring.GetContractPlan(projcode);
                listp = DataToEntity.DataTableToEntityList<ContractPlan>(p) as List<ContractPlan>;
                if (listp != null)
                {
                    info.contractplans = listp;
                }
                return SuccessCenter(info, "true");
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return SuccessCenter("失败", "false");
            }
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> Receive([FromBody] JObject str)
        {
            try
            {
                _logger.Info("收到报文：" + str.ToString());
                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string guiid = Guid.NewGuid().ToString();
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


                //string body = "{\"projcode\":\"" + procode + "\"}";
                //JObject j = JObject.Parse(body);
                //转为链接需要的格式
                str["appkey"] = ConfigHelper.GetConfig().key;
                //string s = str.ToString();
                //s = s.Replace("\"assetid\": \"100\"","\"assetid\": \""+ ConfigHelper.GetConfig().areacode+ "\"");
                //str = JObject.Parse(s);
                JArray ass = JArray.Parse(str["assets"].ToString());
                string orgid = "";
                foreach (JObject js in ass)
                {
                    js["assetid"] = ConfigHelper.GetConfig().areacode + js["assetid"].ToString().Substring(3);
                    orgid = js["orgid"].ToString();
                }
                str.Remove("assets");
                str.Add("assets", ass);
                HttpContent httpContent = new JsonContent(str);
                //client.BaseAddress = new Uri(ConfigHelper.GetConfig().asset);
                client.DefaultRequestHeaders.Add("appkey", ConfigHelper.GetConfig().key);
                client.DefaultRequestHeaders.Add("time", time);
                client.DefaultRequestHeaders.Add("guid", guiid);
                client.DefaultRequestHeaders.Add("sign", APICommond.CreateHeader.ToMD5String(ConfigHelper.GetConfig().key + time + guiid + JsonConvert.SerializeObject(str) + ConfigHelper.GetConfig().secret));
                string result = "";
                HttpResponseMessage response = null;
                try
                {
                    _logger.Info("调用产交接口");
                    response = client.PostAsync(ConfigHelper.GetConfig().asset + "entryassetinformation", httpContent).Result;
                }
                catch (Exception ex1)
                {
                    _logger.Info("调用产交接口失败发送参数为：" + httpContent.ToJson().ToString());
                    _logger.Info("调用产交接口失败" + ex1.Message);
                    return Json(new ResParameter { code = ResponseCode.fail, message = "无法连接产交系统接口" + ex1.Message });
                }
                //string orgid=str[""]
                if (orgid.Contains("320571050"))
                {
                    _logger.Info("调用产交接口成功");
                    Task<string> t = response.Content.ReadAsStringAsync();
                    if (t != null)
                    {
                        result = t.Result;
                        _logger.Info("产交系统返回数据：" + result);
                        JObject j1 = JObject.Parse(t.Result);
                        if (j1["status"].ToString() == "True")
                        {
                            _logger.Info("调用产交系统成功！");
                            if (j1["data"].ToString() != "")
                            {
                                JObject jb = JObject.Parse(j1["data"].ToString());
                                await BusinessRule.Warning.Waring.InsertContract(jb);
                            }
                            string err = await BusinessRule.Warning.Waring.InsertMessage(JsonConvert.SerializeObject(str), JsonConvert.SerializeObject(t.Result));
                            string id = await BusinessRule.Warning.Waring.SaveSendx(str);
                            if (id == "")
                            {
                                _logger.Info("调用产交系统成功，但保存资产发布数据错误！");
                            }
                            else
                            {
                                _logger.Info("保存资产发布数据成功！");
                            }
                            //return Success("成功");
                            //_logger.Info("更新系统数据状态成功，审核成功");
                        }
                        else
                        {
                            string err = await BusinessRule.Warning.Waring.InsertMessage(JsonConvert.SerializeObject(str), JsonConvert.SerializeObject(t.Result));
                            //return Fail("产交系统返回错误信息");
                            _logger.Info("更新系统数据状态失败，产交系统未返回正确数据！");
                            return Json(new ResParameter { code = ResponseCode.fail, message = "产交系统返回错误信息:" + j1["message"].ToString() });
                        }

                    }
                }
                return Success("发送成功");
            }
            catch (Exception ex)
            {
                return Fail("发送失败！" + ex.Message);
            }
        }
        #endregion

        #region "U8"
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetListZCKP(string org = "320571050", string zcbm = "", string zcmc = "", string lbdm = "", int current = 1, int size = 20)
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                //string orgs = await Getorg();
                //if (!org.Contains(orgs))
                //{
                //    org = orgs;
                //}


                (DataTable, int) SelectTable = await BusinessRule.Warning.U8Data.GetListZCKP(org, zcbm, zcmc, lbdm, current, size);

                DataTable table = SelectTable.Item1;
                table = DateString.Dateformat(table);
                Page pa = new Page();
                pa.records = table;
                pa.total = SelectTable.Item2;
                return Success(pa, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetLBDM()
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                DataTable SelectTable = await BusinessRule.Warning.U8Data.GetLBDM();

                List<LBDM> lbdms = new List<LBDM>();
                foreach (DataRow row in SelectTable.Rows)
                {
                    if (Convert.ToString(row["lbdm"]).Trim().Length == 2)
                    {
                        LBDM lbdm = new LBDM();
                        lbdm.lbdm = Convert.ToString(row["lbdm"]).Trim();
                        lbdm.lbmc = Convert.ToString(row["lbmc"]).Trim();
                        List<LBDM> list = new List<LBDM>();
                        foreach (DataRow dr in SelectTable.Rows)
                        {
                            if (Convert.ToString(dr["lbdm"]).Trim().Length == 4 && Convert.ToString(dr["lbdm"]).Trim().Substring(0, 2) == lbdm.lbdm)
                            {
                                LBDM lb = new LBDM();
                                lb.lbdm = Convert.ToString(dr["lbdm"]).Trim();
                                lb.lbmc = Convert.ToString(dr["lbmc"]).Trim();
                                list.Add(lb);
                                List<LBDM> listl = new List<LBDM>();
                                foreach (DataRow r in SelectTable.Rows)
                                {
                                    if (Convert.ToString(r["lbdm"]).Trim().Length == 6 && Convert.ToString(r["lbdm"]).Trim().Substring(0, 4) == lb.lbdm)
                                    {
                                        LBDM l = new LBDM();
                                        l.lbdm = Convert.ToString(r["lbdm"]).Trim();
                                        l.lbmc = Convert.ToString(r["lbmc"]).Trim();
                                        listl.Add(l);
                                    }
                                }
                                lb.list = listl;
                            }
                        }
                        lbdm.list = list;
                        lbdms.Add(lbdm);
                    }

                }


                return Success(lbdms, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }
        #endregion
    }
}
